package com.taotao.rest.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.JsonUtils;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.rest.redis.JedisClient;
import com.taotao.rest.service.ContentService;
@Service
public class ContentServiceImpl implements ContentService {
	@Autowired
	private TbContentMapper contentMapper;
	@Autowired
	private JedisClient jedisClient;
	@Value("${INDEX_CONTENT_REDIS_KEY}")
	private String INDEX_CONTENT_REDIS_KEY; 
	@Override
	public List<TbContent> getContents(Long categoryId) {
		try {
			String hget = jedisClient.hget(INDEX_CONTENT_REDIS_KEY, categoryId+"");
			if(!StringUtils.isBlank(hget)){
				List<TbContent> result = JsonUtils.jsonToList(hget, TbContent.class);
				return result;
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		TbContentExample contentExample=new TbContentExample();
		Criteria criteria = contentExample.createCriteria();
		criteria.andCategoryIdEqualTo(categoryId);
		List<TbContent> contents = contentMapper.selectByExample(contentExample);
		
		//向缓存中添加内容
		try {
			String cacheString=JsonUtils.objectToJson(contents);
			jedisClient.hset(INDEX_CONTENT_REDIS_KEY, categoryId+"", cacheString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return contents;
	}

}
